package com.imooc.controller;

import com.imooc.domain.Result;
import com.imooc.repository.StuRepository;
import com.imooc.service.StuService;
import com.imooc.domain.Student;
import com.imooc.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
public class StuController {

    private final static Logger logger = LoggerFactory.getLogger(StuController.class);

    @Autowired
    private StuRepository stuRepository;

    @Autowired
    private StuService stuService;

    /**
     * 查询所有同学列表
     *
     * @return
     */
    @GetMapping(value = "/students")
    public List<Student> stuList() {
        logger.info("stuList is called.");
        return stuRepository.findAll();
    }

    //添加一个同学
    @PostMapping(value = "/students")
    public Result<Student> stuAdd(@Valid Student student, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());//打印错误信息
        }
        student.setName(student.getName());
        student.setAge(student.getAge());
        student.setScore(student.getScore());
        return ResultUtil.success(stuRepository.save(student));
    }

    //查询一个同学
    @GetMapping(value = "/student/{id}")
    public Student stuFindOne(@PathVariable("id") Integer id) {
        return stuRepository.findById(id).get();
    }

    //通过年龄查询同学（列表）
    @GetMapping(value = "/student/age/{age}")
    public List<Student> stuFindAge(@PathVariable("age") Integer age) {
        return stuRepository.findByAge(age);
    }

    //更新一个同学
    @PutMapping(value = "/student/{id}")
    public Student stuUpdate(@PathVariable("id") Integer id,
                             @RequestParam("name") String name,
                             @RequestParam("age") Integer age,
                             @RequestParam("score") Double score) {
        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setAge(age);
        student.setScore(score);
        return stuRepository.save(student);
    }

    //删除一个同学
    @DeleteMapping(value = "/student/{id}")
    public void stuDelete(@PathVariable("id") Integer id) {
        stuRepository.deleteById(id);
    }

    //同时添加两个同学
    @PostMapping(value = "/student/two")
    public void stuTwo() {
        stuService.insertTwo();
    }

    @GetMapping(value = "/students/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws  Exception{
        stuService.getAge(id);//所有的逻辑都尽量在 Service 完成
    }
}
